<!DOCTYPE html>
<html lang="zh-CN">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>工具提示行为</title>
		<style>
			body {
				height: 2000px;
				/* make body scrollable, the tooltip should work after the scroll */
			}

			.tooltip {
				/* some styles for the tooltip, you can use your own instead */
				position: fixed;
				padding: 10px 20px;
				border: 1px solid #b3c9ce;
				border-radius: 4px;
				text-align: center;
				font: italic 14px/1.3 sans-serif;
				color: #333;
				background: #fff;
				box-shadow: 3px 3px 3px rgba(0, 0, 0, 0.3);
			}
		</style>
	</head>
	<body>
		<p>LaLaLa LaLaLa LaLaLa LaLaLa LaLaLa LaLaLa LaLaLa LaLaLa LaLaLa</p>
		<p>LaLaLa LaLaLa LaLaLa LaLaLa LaLaLa LaLaLa LaLaLa LaLaLa LaLaLa</p>

		<button data-tooltip="the tooltip is longer than the element">Short button</button>
		<button data-tooltip="HTML<br>tooltip">One more button</button>

		<p>Scroll the page to make buttons appear on the top, check if the tooltips show up correctly.</p>

		<script>
			let div

			// 鼠标移入
			document.addEventListener('mouseover', (e) => {
				const tooltip = e.target.dataset.tooltip
				if (!tooltip) return

				div = document.createElement('div')
				div.className = 'tooltip'
				div.innerHTML = tooltip

				document.body.append(div)

				let targetRect = e.target.getBoundingClientRect()
				let divRect = div.getBoundingClientRect()

				// tips 出现在上方的位置
				if (targetRect.top < divRect.height) {
					div.style.top = targetRect.bottom + 5 + 'px'
				} else {
					// tips 出现在下方的位置
					div.style.top = targetRect.top - divRect.height - 5 + 'px'
				}

				if (divRect.width < targetRect.width) {
					let w = (targetRect.width - divRect.width) / 2
					div.style.left = targetRect.left + w + 'px'
				}

				// 鼠标移出
				e.target.addEventListener('mouseout', (e) => {
					div.remove()
				})
			})
		</script>
	</body>
</html>
